package com.wn.naturalbiorhythms.view;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TreeMap;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.PathEffect;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;

import com.wn.naturalbiorhythms.R;
import com.wn.naturalbiorhythms.bean.NaturalValue;
import com.wn.naturalbiorhythms.tool.BirthdaySettingsSharePref;
import com.wn.naturalbiorhythms.tool.NaturalBiorhythmsAlgorithm;

public class NaturalBiorhythmsView extends View {

	private Paint paint = new Paint();
	private Context context;
	private float x_left = 10.0f, x_right = 0.0f;
	private float y_top = 20.0f, y_bottom = 0.0f;
	private byte[]showDays = {7,17,23,28,33};
	private byte[]textSizeList = {20,18,16,14,12};
	// 显示数量
	private int px = showDays[1];
	private byte textSize = textSizeList[1];

	private float height;
	private float width;

	//private SimpleDateFormat sdf_date = new SimpleDateFormat("yyyy-MM-dd");

	private SimpleDateFormat sdf_month = new SimpleDateFormat("yyyy-MM");

	private final String[] week;

	//public static final long oneDayMilliseconds = 24 * 60 * 60 * 1000;
	public static final byte T_physical = 23;
	public static final byte T_emotional = 28;
	public static final byte T_intellictual = 33;
	public static final byte T_intuitive = 38;
	
	public static final byte Day_Cycle = 0;//周期日
	public static final byte Day_Critical_physical = 12;//体力临界日
	public static final byte Day_Critical_emotional = 14;//情绪临界日
	public static final byte Day_Critical_intellictual = 17;//智力临界日
	public static final byte Day_Critical_intuitive = 19;//直觉临界日

	private float ratio = 0.00f;

	private long startdayMilliseconds;
	private long startday;
	private long birthdayMilliseconds;
	private long totalDaysMilliseconds;
	private long totalDays;
	private long movetoMilliseconds;

	private final String PHYSICAL_TEXT;
	private final String EMOTIONAL_TEXT;
	private final String INTELLICTUAL_TEXT;
	private final String INTUITIVE_TEXT;
	private final String MAO_HAO;
	private final String DAYS_LIVED;
	
	private final String drawPic_Cycle;
	private final String drawPic_Critical;
	private final String drawPic_H;
	private final String drawPic_L;
	
	//private Date birthday = null;
	private Date today = null;
	private NaturalBiorhythmsAlgorithm nba;
	
	private NaturalValue todayNvalue;
	
	private float x_step;
	
	private TreeMap<Float, NaturalValue> nValueMap = new TreeMap<Float, NaturalValue>();
	private List<Float>xKeys = new ArrayList<Float>();
	private BirthdaySettingsSharePref bsspref;
	public NaturalBiorhythmsView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context; 
		PHYSICAL_TEXT = this.context.getString(R.string.physical);
		EMOTIONAL_TEXT = this.context.getString(R.string.emotional);
		INTELLICTUAL_TEXT = this.context.getString(R.string.intellictual);
		INTUITIVE_TEXT = this.context.getString(R.string.intuitive);
		DAYS_LIVED = this.context.getString(R.string.days_lived);
		MAO_HAO = this.context.getString(R.string.maohao_text)+" ";
		week = this.context.getResources().getStringArray(R.array.week_days);
		
		drawPic_Cycle = this.context.getString(R.string.DayInCycle_Cycle_pic);
		drawPic_Critical = this.context.getString(R.string.DayInCycle_Critical_pic);
		drawPic_H = this.context.getString(R.string.DayInCycle_Climax_pic);
		drawPic_L = this.context.getString(R.string.DayInCycle_Lowtide_pic);
		
		DisplayMetrics display = this.context.getResources().getDisplayMetrics();
		height = display.heightPixels;
		width = display.widthPixels;
		x_left = width*(float)0.035;
		x_right =x_left + width*(float)0.90;
		y_top = height *(float)0.03;
		y_bottom =y_top + height * (float)0.44;
		
		bsspref = BirthdaySettingsSharePref.getInstance(this.context);
		
		try {
			today = NaturalBiorhythmsAlgorithm.SDF_DATE_yyyy_MM_dd.parse(NaturalBiorhythmsAlgorithm.SDF_DATE_yyyy_MM_dd.format(new Date()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		setBirthday();
		
	}

	public void setToday(long todayMilliseconds) {
		startdayMilliseconds = todayMilliseconds - birthdayMilliseconds
				- (px / 2) * NaturalBiorhythmsAlgorithm.ONE_DAY_MILLISECONDS;
		startday = startdayMilliseconds / NaturalBiorhythmsAlgorithm.ONE_DAY_MILLISECONDS;
		movetoMilliseconds = todayMilliseconds;
		invalidate();
	}

	public void setStart(long milliseconds, int flag) {
		startdayMilliseconds += flag * milliseconds;
		startday = startdayMilliseconds / NaturalBiorhythmsAlgorithm.ONE_DAY_MILLISECONDS;
		if (startdayMilliseconds < 0 || startday < 0) {
			startdayMilliseconds = 0;
			startday = 0;
		}
		movetoMilliseconds = startdayMilliseconds + (px / 2)
				* NaturalBiorhythmsAlgorithm.ONE_DAY_MILLISECONDS + birthdayMilliseconds;
		invalidate();
	}

	public void setStart(int num, int flag) {
		startdayMilliseconds += flag * num * NaturalBiorhythmsAlgorithm.ONE_DAY_MILLISECONDS;
		startday += flag * num;
		if (startdayMilliseconds < 0 || startday < 0) {
			startdayMilliseconds = 0;
			startday = 0;
		}
		invalidate();
	}

	public void resetStart() {
		startdayMilliseconds = 0;
		startday = 0;
		movetoMilliseconds = birthdayMilliseconds;
		invalidate();
	}

	public void setBirthday() {
	
		birthdayMilliseconds = bsspref.getBirthday((byte)0);
		nba = new NaturalBiorhythmsAlgorithm(birthdayMilliseconds);
		totalDays = nba.getLivedDays();
		totalDaysMilliseconds = nba.getLivedDaysMilliseconds();
		startdayMilliseconds = totalDaysMilliseconds - (px / 2) * NaturalBiorhythmsAlgorithm.ONE_DAY_MILLISECONDS;
		startday = totalDays - (px / 2);
	}
	
	public void setShowDays(byte showDays,byte textsize){
		px = showDays;
		textSize = textsize;
		invalidate();
	}

	private boolean isChina_zh(){
		return (Locale.getDefault().getLanguage().equals("zh"));
	}
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// 这个一定要调用， 告诉系统测量的最终结果 需要的宽度是width 高度是height
		setMeasuredDimension((int)(width*(float)0.97),(int)(height * (float)0.55) );

	}

	@Override
	protected void onDraw(Canvas canvas) {
		paint.reset();
		ratio = (y_top - y_bottom) / 240;
		paint.setColor(Color.GRAY);
		paint.setStyle(Style.STROKE);
		canvas.drawRect(x_left, y_top, x_right, y_bottom, paint);
		// 绘画横中线
		float y_middle = y_top + (y_bottom - y_top) / 2;
		canvas.drawLine(x_left, y_middle, x_right, y_middle, paint);

		// 曲线对象
		MyDraw line1 = new MyDraw();
		MyDraw line2 = new MyDraw();
		MyDraw line3 = new MyDraw();
		MyDraw line4 = new MyDraw();
		//
		MyDraw todayArea = new MyDraw();
		// 绘画纵线

		xKeys.clear();
		nValueMap.clear();
		x_step = (x_right - x_left) / px;
		for (int i = 0; i < px; i++) {
			float x = x_left + i * x_step;
			paint.setColor(Color.GRAY);
			canvas.drawLine(x, y_top, x, y_bottom, paint);

			if(startday + i<0){
				continue;
			}
			
			float dx = x + x_step / 2;
			float dy1_v = NaturalBiorhythmsAlgorithm.getValuePhysical(startday, i);
			float dy1 = toScreenY(dy1_v);
			
			float dy2_v = NaturalBiorhythmsAlgorithm.getValueEmotional(startday, i);
			float dy2 = toScreenY(dy2_v);
			
			float dy3_v = NaturalBiorhythmsAlgorithm.getValueIntellictual(startday, i);
			float dy3 = toScreenY(dy3_v);
			
			float dy4_v = NaturalBiorhythmsAlgorithm.getValueIntuitive(startday, i);
			float dy4 = toScreenY(dy4_v);

			// 初始化开始点
			//if (i == 0) {
				line1.init(dx, dy1);
				line2.init(dx, dy2);
				line3.init(dx, dy3);
				line4.init(dx, dy4);
			//}
			
			//
			Calendar cal = Calendar.getInstance();
			cal.setTimeInMillis(startdayMilliseconds + i
					* NaturalBiorhythmsAlgorithm.ONE_DAY_MILLISECONDS + birthdayMilliseconds);
			NaturalValue nv= new NaturalValue(dy1_v, dy2_v, dy3_v, dy4_v,cal,birthdayMilliseconds);
			xKeys.add(Float.valueOf(x));
			nValueMap.put(Float.valueOf(x), nv);

			//
			
			// 绘画曲线
			/* 去锯齿 */
			paint.setAntiAlias(true);
			paint.setStrokeWidth(1.2f);
			paint.setColor(Color.parseColor(this.context.getString(R.color.color_physical)));
			line1.drawLine(dx, dy1, canvas);
			line1.drawPoint(dx, dy1, canvas, nv.getTypeInCyclePhysical());
			
			paint.setColor(Color.parseColor(this.context.getString(R.color.color_emotional)));
			line2.drawLine(dx, dy2, canvas);
			line2.drawPoint(dx, dy2, canvas, nv.getTypeInCycleEmotional());
			
			paint.setColor(Color.parseColor(this.context.getString(R.color.color_intellictual)));
			line3.drawLine(dx, dy3, canvas);
			line3.drawPoint(dx, dy3, canvas, nv.getTypeInCycleIntellictual());
			
			paint.setColor(Color.parseColor(this.context.getString(R.color.color_intuitive)));
			line4.drawLine(dx, dy4, canvas);
			line4.drawPoint(dx, dy4, canvas, nv.getTypeInCycleIntuitive());
			
			paint.reset();
			// ////////////////////////
			
			// 将今天特色显示////////////////
			if (cal.getTimeInMillis() == today.getTime()) {
				todayArea.init(x, y_top);
				todayNvalue = new NaturalValue(dy1_v, dy2_v, dy3_v, dy4_v,cal,birthdayMilliseconds);
			}
			if (cal.getTimeInMillis() == (today.getTime() + NaturalBiorhythmsAlgorithm.ONE_DAY_MILLISECONDS)) {
				paint.setStyle(Style.FILL);
				paint.setARGB(64, 0x66, 0xCC, 0x66);
				todayArea.drawArea(x, y_bottom, canvas);
				paint.reset();
			}

			paint.setColor(Color.rgb(0x00, 0x00, 0x33));
			int day = cal.get(Calendar.DAY_OF_MONTH);

			// 绘画年月
			if (i == (px / 2)) {
				paint.setTextAlign(Align.CENTER);
				paint.setTextSize(18);
				String text = sdf_month.format(cal.getTime());
				if (day >= 28) {
					paint.setTextAlign(Align.RIGHT);
				}
				if (day - 1 <= 0) {
					paint.setTextAlign(Align.LEFT);
				}
				canvas.drawText(text, dx, y_top - 5, paint);
				paint.reset();
			}
			if (cal.getTimeInMillis() == movetoMilliseconds) {
				paint.setColor(Color.rgb(0x66, 0xCC, 0x00));
				paint.setTypeface(Typeface.DEFAULT_BOLD);
			}
			paint.setTextAlign(Align.CENTER);
			paint.setTextSize(textSize);
			// 绘画日期
			canvas.drawText("" + day, dx, y_top + 14, paint);
			// 绘画星期
			canvas.drawText(week[cal.get(Calendar.DAY_OF_WEEK) - 1], dx,
					y_bottom - 2, paint);
			paint.reset();
		}
		
		//多加一个点的数据，方便比较最后一个数据的趋势
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(startdayMilliseconds + px
				* NaturalBiorhythmsAlgorithm.ONE_DAY_MILLISECONDS + birthdayMilliseconds);
		NaturalValue nv= new NaturalValue(NaturalBiorhythmsAlgorithm.getValuePhysical(startday, px), 
				NaturalBiorhythmsAlgorithm.getValueEmotional(startday, px), 
				NaturalBiorhythmsAlgorithm.getValueIntellictual(startday, px), 
				NaturalBiorhythmsAlgorithm.getValueIntuitive(startday, px),
				cal,
				birthdayMilliseconds);
		xKeys.add(Float.valueOf(x_right+x_step));
		nValueMap.put(Float.valueOf(x_right+x_step), nv);
		//结束多加
		
		float xs = x_left + 5;
		//绘制生日
		paint.setTextSize(18);
		canvas.drawText(nba.getBirthday(), xs, y_top - 5, paint);
		//经历天数
		paint.setTextAlign(Align.RIGHT);
		canvas.drawText(DAYS_LIVED+MAO_HAO + totalDays, x_right, y_top - 5, paint);
		
		// 样例说明
		paint.reset();
		paint.setTextSize(18);
		paint.setColor(Color.parseColor(this.context.getString(R.color.color_physical)));
		
		float ys = y_bottom + 18;
		String LINE = MAO_HAO +todayNvalue.getPhysical();
		
		if(isChina_zh()){
			canvas.drawText(PHYSICAL_TEXT + LINE, xs, ys, paint);
			xs += paint.measureText(PHYSICAL_TEXT + LINE) + 10;
			paint.setColor(Color.parseColor(this.context.getString(R.color.color_emotional)));
			
			LINE = MAO_HAO+todayNvalue.getEmotional();
			canvas.drawText(EMOTIONAL_TEXT + LINE, xs, ys, paint);
			xs += paint.measureText(EMOTIONAL_TEXT + LINE) + 10;
			paint.setColor(Color.parseColor(this.context.getString(R.color.color_intellictual)));
			LINE = MAO_HAO+todayNvalue.getIntellictual();
			canvas.drawText(INTELLICTUAL_TEXT + LINE, xs, ys, paint);
			xs += paint.measureText(INTELLICTUAL_TEXT + LINE) + 10;
			paint.setColor(Color.parseColor(this.context.getString(R.color.color_intuitive)));
			LINE = MAO_HAO+todayNvalue.getIntuitive();
			canvas.drawText(INTUITIVE_TEXT + LINE, xs, ys, paint);
		}else{
			
			canvas.drawText(PHYSICAL_TEXT + LINE, xs, ys, paint);
			
			xs +=(x_right - x_left)/2;
			paint.setColor(Color.parseColor(this.context.getString(R.color.color_emotional)));
			LINE = MAO_HAO+todayNvalue.getEmotional();
			canvas.drawText(EMOTIONAL_TEXT + LINE, xs, ys, paint);
			
			xs = x_left + 5;
			paint.setColor(Color.parseColor(this.context.getString(R.color.color_intellictual)));
			LINE = MAO_HAO+todayNvalue.getIntellictual();
			canvas.drawText(INTELLICTUAL_TEXT + LINE, xs, ys+19, paint);
			
			xs +=(x_right - x_left)/2;
			paint.setColor(Color.parseColor(this.context.getString(R.color.color_intuitive)));
			LINE = MAO_HAO+todayNvalue.getIntuitive();
			canvas.drawText(INTUITIVE_TEXT + LINE, xs, ys+19, paint);
		}
		

		//paint.setColor(Color.rgb(0x00, 0x00, 0x33));
		//paint.setTextAlign(Align.RIGHT);
		//canvas.drawText(DAYS_LIVED+MAO_HAO + totalDays, x_right, ys, paint);
		//canvas.drawText(DAYS_LIVED+MAO_HAO + totalDays, x_left + 5, ys+19, paint);
		paint.reset();

		// 绘画横线， 虚线样式
		PathEffect mEffects = new DashPathEffect(
				new float[] { 1, 1, 1, 1 }, 1);
		paint.setPathEffect(mEffects);
		paint.setColor(Color.GRAY);
		paint.setAlpha(125);
		int py = 10;
		float y_step = (y_bottom - y_top) / py;
		for (int i = 1; i < py; i++) {
			float y = y_top + y_step * i;
			canvas.drawLine(x_left, y, x_right, y, paint);
		}

	}

	private float toScreenY(float value) {
		return y_bottom - 30 + (value + 100) * ratio;
	}

	/***/
	class MyDraw {

		private boolean init = false;
		float last_x = 0.00f;
		float last_y = 0.00f;

		public void init(float x0, float y0) {
			if(init){
				return;
			}
			last_x = x0;
			last_y = y0;
			init = true;
		}
		
		public boolean isInit(){
			return init;
		}

		public void drawLine(float stopX, float stopY, Canvas canvas) {
			canvas.drawLine(last_x, last_y, stopX, stopY, paint);
			last_x = stopX;
			last_y = stopY;

		}

		public void drawArea(float stopX, float stopY, Canvas canvas) {
			canvas.drawRect(last_x, last_y, stopX, stopY, paint);
		}
		int i;
		public void drawPoint(float stopX, float stopY, Canvas canvas,byte type){
			String text = "";
			if(type == 0){
				text = drawPic_Cycle;
			}else if(type == 1){
				text = drawPic_H;
			}else if(type == 2){
				text = drawPic_Critical;
			}else{
				text = drawPic_L;
			}
			paint.setTypeface(Typeface.DEFAULT);
			paint.setTextAlign(Align.CENTER);
			canvas.drawText(text, stopX, stopY, paint);
			//Log.i("MyDraw", "drawPoint "+(i++)+",stopX="+stopX+",stopY="+stopY);
			//canvas.drawText(text, last_x, last_y, paint);
		}
	}
	
	
	/*public float getXstep(){
		return x_step;
	}*/

	public long getBirthdayMilliseconds() {
		return birthdayMilliseconds;
	}

	/*public long getOneDayMilliseconds() {
		return NaturalBiorhythmsAlgorithm.ONE_DAY_MILLISECONDS;
	}*/

	public List<Float> getxKeys() {
		return xKeys;
	}

	public TreeMap<Float, NaturalValue> getnValueMap() {
		return nValueMap;
	}
	
	public NaturalBiorhythmsAlgorithm getNBAlgorithm(){
		return nba;
	}

	public float getY_bottom() {
		return y_bottom;
	}

	public float getX_left() {
		return x_left;
	}

	public float getX_right() {
		return x_right;
	}

	public float getY_top() {
		return y_top;
	}

}
